//
//  RHLocalCellVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/8.
//

#import "RHLocalCellVC.h"
#import "RHLocalCellItemCell.h"
#import "RHDevPackModel.h"
#import "RHLocalBatteryCellFullChartVC.h"
#import "RHLocalSettingModel.h"
#import "RHBleCmdManager.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "JCDataConvert.h"

@interface RHLocalCellVC ()
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectView;

@property (nonatomic, strong) NSArray *cellDataArr;


//读取完电芯单体个数和温度个数
@property (nonatomic ,assign) BOOL hasReadVolTempCount;
//读取完电芯电压和温度值
@property (nonatomic ,assign) BOOL hasReadVolTempValue;

//单体电压数量
@property (nonatomic ,assign) NSInteger cellVolCount;
//单体温度数量,两个单体共用一个温度
@property (nonatomic ,assign) NSInteger cellTempCount;

//电芯电压数据
@property (nonatomic ,strong) NSMutableArray *volDataArr;
//电芯温度数据
@property (nonatomic ,strong) NSMutableArray *tempDataArr;
@end

@implementation RHLocalCellVC

-(void)viewDidLoad {
   [super viewDidLoad];
   [self setupUI];
    [self readPackCount];
}

#pragma mark ---------  读取单体个数和温度个数 -----
-(void)readPackCount
{
    
    self.hasReadVolTempValue = NO;
    NSArray *packArr = @[@{
        @"field":@"Pck_CellV_Cnt",
        @"regAddr":@(1000),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101+self.packIndex)
    },@{
        @"field":@"Pck_Tmp_Cnt",
        @"regAddr":@(2000),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101+self.packIndex)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [packArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
    }];
    NSLog(@"---->读取单体个数和温度个数")
    self.cmdArray = mtbArr.copy;
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
    
    
}

#pragma mark ---------  读取具体的电压和温度  最高,最低位置,压差-----
-(void)readCellVoltageAndTemperature
{
    if(self.hasReadVolTempValue){
        [self creatCellModelData];
        NSLog(@"------->读取电压和温度值完毕");
        return;
    }
    
    NSArray *volTempArr = @[@{
        @"field":@"Pck_CellV_1",
        @"regAddr":@(1001),
        @"bitWidth":@(16),
        @"ratio":@"1",
        @"cmdType":@(101+self.packIndex)
    },@{
        @"field":@"Pck_Tmp_1",
        @"regAddr":@(2001),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(101+self.packIndex)
    }];
    NSMutableArray *mtbArr = [NSMutableArray array];
    [volTempArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        if([settingModel.field isEqualToString:@"Pck_CellV_1"]){
            //设置读取电压个数
            settingModel.readAddrCount = self.cellVolCount;
        }
        if([settingModel.field isEqualToString:@"Pck_Tmp_1"]){
            //设置读取温度个数
            settingModel.readAddrCount = self.cellTempCount;
        }
        [mtbArr addObject:settingModel];
    }];
    NSLog(@"---->读取单体个数和温度个数")
    self.cmdArray = mtbArr.copy;
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}


-(void)receiveDeviceMsg:(NSNotification *)no
{
    [super receiveDeviceMsg:no];
    NSDictionary *dic = [no object];
    if(!self.recieveMsg)return;
    
    if(dic.allKeys.count==0)return;
    NSLog(@"------>收到设备信息:%@",dic);
    
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);
            
            
            [self.dataDic setObject:parse_content forKey:obj.field];
            //读取到电芯电压数量
            if([obj.field isEqualToString:@"Pck_CellV_Cnt"]){
                self.cellVolCount = [parse_content integerValue];
            }
            
            //读取到温度数量
            if([obj.field isEqualToString:@"Pck_Tmp_Cnt"]){
                self.hasReadVolTempCount = YES;
                self.cellTempCount = [parse_content integerValue];
            }
            
            //读取到电压值
            if([obj.field isEqualToString:@"Pck_CellV_1"]){
               
                for (int i = 0; i < self.cellVolCount; i ++) {
                    NSData *volData = [data subdataWithRange:NSMakeRange(i*2, 2)];
                    NSInteger volValue = [JCDataConvert dataToInt:volData];
                    if(self.volDataArr.count>i){
                        [self.volDataArr replaceObjectAtIndex:i withObject:@(volValue)];
                        
                    }else{
                        [self.volDataArr addObject:@(volValue)];
                    }
                    
                }
               
            }
            
            //读取到温度值
            if([obj.field isEqualToString:@"Pck_Tmp_1"]){
                self.hasReadVolTempValue = YES;
                for (int i = 0; i < self.cellTempCount; i ++) {
                    NSData *tempData = [data subdataWithRange:NSMakeRange(i*2, 2)];
                    double value = [JCDataConvert dataToSignedInt:tempData]*[obj.ratio doubleValue];
                    NSLog(@"------>温度:%lf",value);
                    NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithDouble:value];
                    if(self.tempDataArr.count>i){
                        [self.tempDataArr replaceObjectAtIndex:i withObject:num];
                    }else{
                        
                        [self.tempDataArr addObject:num];
                    }
                   
                }
               
            }
   
        };
           
    }];
    
   
    [self.collectView reloadData];
    
}

#pragma mark -------- 命令发送完
-(void)sendCmdFinish
{
    if(self.recieveMsg == NO)return;
    NSLog(@"---->读取到的设备信息:%@",self.dataDic);
  
    //读取完单体个数和温度个数就读具体的单体电压值和温度值
    if(self.hasReadVolTempCount){
        [self readCellVoltageAndTemperature];
    }else{
        //读取单体个数和温度个数,两个单体共用一个温度
        [self readPackCount];
    }
    
    [self.collectView endHeaderRefresh];
}

-(void)creatCellModelData
{
    NSMutableArray *mtbArr = [NSMutableArray array];
    for (int i = 0; i < self.volDataArr.count; i++) {
        RHDevCellModel *cellModel = [[RHDevCellModel alloc]init];
        cellModel.volt = [NSString stringWithFormat:@"%@",self.volDataArr[i]];

        cellModel.temp = [NSString stringWithFormat:@"%@",self.tempDataArr[i/2]];
        
        
        
        [mtbArr addObject:cellModel];
    }
    self.cellDataArr = mtbArr.copy;
    [self.collectView reloadData];
}


-(void)setupUI
{
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    
    UIView *topView = kView;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.mas_offset(30);
    }];
    UIView *normalPoint = kView;
    normalPoint.backgroundColor = kRGB(57, 222, 63);
    normalPoint.layer.cornerRadius = 5;
    [topView addSubview:normalPoint];
    [normalPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(10, 10)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *norLab = [QMUILabel labelWithText:@"正常电芯".rh_localized font:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.6)];
    [topView addSubview:norLab];
    [norLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(normalPoint.mas_right).offset(15);
        make.centerY.equalTo(normalPoint);
    }];
    
    UIView *faultPoint = kView;
    faultPoint.backgroundColor = kRGB(255, 108, 97);
    faultPoint.layer.cornerRadius = 5;
    [topView addSubview:faultPoint];
    [faultPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(10, 10)));
        make.left.equalTo(norLab.mas_right).offset(25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *faultLab = [QMUILabel labelWithText:@"高温电芯".rh_localized font:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.6)];
    [topView addSubview:faultLab];
    [faultLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(faultPoint.mas_right).offset(15);
        make.centerY.equalTo(normalPoint);
    }];
    
    UIView *lowPoint = kView;
    lowPoint.backgroundColor = kRGB(38, 111, 232);
    lowPoint.layer.cornerRadius = 5;
    [topView addSubview:lowPoint];
    [lowPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(10, 10)));
        make.left.equalTo(faultLab.mas_right).offset(25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *lowLab = [QMUILabel labelWithText:@"低温电芯".rh_localized font:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.6)];
    [topView addSubview:lowLab];
    [lowLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lowPoint.mas_right).offset(15);
        make.centerY.equalTo(lowPoint);
    }];
    
   UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
   _collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
   _collectView.backgroundColor = CFTabViewBgColor;
   _collectView.showsVerticalScrollIndicator = NO;
   _collectView.showsHorizontalScrollIndicator = NO;
   _collectView.delegate = self;
   _collectView.dataSource = self;
   [_collectView registerClass:[RHLocalCellItemCell class] forCellWithReuseIdentifier:@"RHLocalCellItemCell"];
   [self.view addSubview:_collectView];
   
   
   [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.equalTo(topView.mas_bottom);
       make.left.right.mas_offset(0);
       make.bottom.mas_offset(0);
   }];
   kWeakSelf;
   [_collectView addHeaderRefresh:^{
       [weakSelf readPackCount];
   }];
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
   return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
   
    return self.cellDataArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
       RHLocalCellItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RHLocalCellItemCell" forIndexPath:indexPath];
       RHDevCellModel *model = self.cellDataArr[indexPath.item];
//       model.temp = indexPath.item%2? @"60":@"-26";
       cell.cellModel = model;
       cell.packNoLab.text = [NSString stringWithFormat:@"%@ %ld",@"电芯".rh_localized,indexPath.item+1];
    
       kWeakSelf;
       cell.chartBlock = ^{
           RHLocalBatteryCellFullChartVC *loadVC = [[RHLocalBatteryCellFullChartVC alloc]initWithPackIndex:weakSelf.packIndex cellIndex:indexPath.item];
           loadVC.title = [NSString stringWithFormat:@"%ld#%@",indexPath.item+1,@"电芯".rh_localized];
           [weakSelf.navigationController pushViewController:loadVC animated:NO];
       };
       return cell;

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
  
       CGFloat w = (kUI_WINDOW_W -45)/2;
       CGFloat h = w * 0.65;
       return CGSizeMake(w, h);
   
   
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
   
   return UIEdgeInsetsMake(15, 15, 15, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
   
   return 15;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
   
   return 15;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

}

-(UIView *)listView
{
    return self.view;
}


-(NSMutableArray *)volDataArr
{
    if(!_volDataArr){
        _volDataArr = [NSMutableArray array];
    }
    return _volDataArr;
}

-(NSMutableArray *)tempDataArr
{
    if(!_tempDataArr){
        _tempDataArr = [NSMutableArray array];
    }
    return _tempDataArr;
}
@end
